using System;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared.SharedTypes;
using OST.Persistence;
using OST.Shared;

namespace OST.Commands
{
    using Extensions;

    /// <summary>
    /// returns the actual xml-serialized-Configuration
    /// </summary>
    public class ConfigurationGETCommand : mfRcfCommand
    {
        #region CTOR

        public ConfigurationGETCommand(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// wrapper-property 4 logging
        /// </summary>
        private ILoggerAppender Logger
        {
            get
            {
                return mfLogger.mfLogger.Instance;
            }
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            try
            {
                if (!ConfigurationProvider.Instance.HasConfig)
                    throw new OSTException("no config loaded");

                var configSerializer = new mfXmlTypedSerializer(typeof(Configuration));

                httpContext.Response.ContentType = ContentTypeOut;
                httpContext.Response.StatusCode = enumHttpStatusCode.OK;

                //serialze(on) xml --> is too-memory-intensive, string copy seems to be more efficient
                //configSerializer.SerializeOnStream(ConfigurationProvider.Instance.ConfigInstance
                //                                    , httpContext.Response.OutputStream);
                var configXmlString = configSerializer.Serialize(ConfigurationProvider.Instance.ConfigInstance);
                configSerializer.Dispose();

                httpContext.Response.OutputStream.WriteString(configXmlString);
                configXmlString = null;
                httpContext.Response.Close();

                Logger.Debug(GetType() + " executed, " + Debug.GC(true) + " bytes free");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }
        #endregion
    }
}
